package com.kxf.androidtestdemo.fragments;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.ContentInfoCompat;

import com.kxf.androidtestdemo.activity.ServiceActivity;
import com.kxf.androidtestdemo.bean.ActivityResultCallbackBean;

public class ActivityResultCallbackFragment extends BaseFragment {

    ActivityResultContract activityResultContract = new ActivityResultContract<Intent, ActivityResultCallbackBean>() {
        @NonNull
        @Override
        public Intent createIntent(@NonNull Context context, Intent input) {
            return input;
        }

        @Override
        public ActivityResultCallbackBean parseResult(int resultCode, @Nullable Intent intent) {
            ActivityResultCallbackBean bean = new ActivityResultCallbackBean();
            if (intent != null){
                bean.setCode(intent.getIntExtra("code", -1));
                bean.setResultStr(intent.getStringExtra("resultStr"));
            }
            return bean;
        }
    };
    ActivityResultCallback callback = new ActivityResultCallback<ActivityResultCallbackBean>() {
        @Override
        public void onActivityResult(ActivityResultCallbackBean result) {
            Log.d("onActivityResult", "result=" + result);
        }
    };
    private ActivityResultLauncher resultLauncher;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        resultLauncher = registerForActivityResult(activityResultContract, callback);
    }

    @Override
    protected int getLayoutRes() {
        return 0;
    }

    @Override
    protected void initView() {

    }

    public void mStartActivityForResult(Class<?> cls) {
        startActivityForResult(new Intent(getActivity(), cls), 120);
    }

    public void mResultLauncherActivity(Class<?> cls) {
        resultLauncher.launch(new Intent(getActivity(), cls));
    }

    public void mResultLauncherActivity(Class<?> cls, int flags) {
        Intent intent = new Intent(getActivity(), cls);
        intent.setFlags(flags);
        resultLauncher.launch(intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
